﻿using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using System.Collections.Generic;

namespace FarmSmartSleep.Organ.API.Application.SleepInfoCommands.FemaleBeginCommands
{
    public class FemaleBeginCreateHandler : IRequestHandler<FemaleBeginCreateCommand, Result>
    {
        IBaseRepository<FemaleBegin> femaleBeginRep;
        IBaseRepository<SleepInfor> sleepinforRep;

        public FemaleBeginCreateHandler(IBaseRepository<FemaleBegin> femaleBeginRep, IBaseRepository<SleepInfor> sleepinforRep)
        {
            this.femaleBeginRep = femaleBeginRep;
            this.sleepinforRep = sleepinforRep;
        }

        /// <summary>
        /// 种母期初添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(FemaleBeginCreateCommand request, CancellationToken cancellationToken)
        {
            var query = new Result() { Code = (int)CodeEnum.success };

            var data = femaleBeginRep.Add(request.GetFemaleBegin);

            if (data > 0)
            {
                //当添加成功时，对种母档案中的栋舍栏位和在场状态进行修改
                var res = sleepinforRep.GetAll().FirstOrDefault(x => x.SleepInforId == request.GetFemaleBegin.SleepInforId);
                if (res != null)
                {
                    res.StayStatus = 1;
                    res.RecordcottageId = request.GetFemaleBegin.CottagesId;
                    res.FieIdId = request.GetFemaleBegin.Field;
                    sleepinforRep.Update(res);
                }
            }
            query.Code = data;
            return query;
        }
    }
}
